/*
scheduler 的默认精度为秒

callback() 不会出现并发！
当 callback() 处理时常超过 duration 时，抛出一条警告日志，并放弃本次 callback() 的执行

记得调用 scheduler.Start()
*/
package scheduler

func Once(name string, after int64, callback func()) {
	newScheduler(name, Now()+after, 0, 1, 0, callback)
}

func Specific(name string, duration int64, times int32, callback func()) {
	newScheduler(name, Now(), duration, times, 0, callback)
}

func Forever(name string, duration int64, callback func()) {
	newScheduler(name, Now(), duration, -1, 0, callback)
}

func CronOnce(name string, startAt int64, callback func()) {
	if startAt < Now() {
		newScheduler(name, startAt, 0, 1, 1, callback) // 跳过一次
	} else {
		newScheduler(name, startAt, 0, 1, 0, callback)
	}
}

// startAt 第一次执行时间
func CronSpecific(name string, startAt int64, duration int64, times int32, callback func()) {
	if startAt < Now() {
		newScheduler(name, startAt, duration, times, 1, callback) // 跳过一次
	} else {
		newScheduler(name, startAt, duration, times, 0, callback)
	}
}

// startAt 第一次执行时间
func CronForever(name string, startAt int64, duration int64, callback func()) {
	if startAt < Now() {
		newScheduler(name, startAt, duration, -1, 1, callback) // 跳过一次
	} else {
		newScheduler(name, startAt, duration, -1, 0, callback)
	}
}

func Delete(isDelete func(name string) bool) {
	schedulers.Range(func(key, value any) bool {
		if isDelete(key.(string)) {
			schedulers.Delete(key)
		}

		return true
	})
}
